package org.fall.system.config.interceptor;

import lombok.extern.log4j.Log4j2;
import org.fall.system.annotation.AdminRoleCheckAnnotation;
import org.fall.system.exception.AdminUserAuthException;
import org.fall.system.utils.ServletUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 管理员用户角色-拦截器
 * @author sprogFall
 * @since 2021/4/10 13:40
 */
@Component
@Log4j2
public class AdminUserRoleHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 对标注了@AdminRoleCheckAnnotation的方法进行权限认证
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        AdminRoleCheckAnnotation annotation = handlerMethod.getMethodAnnotation(AdminRoleCheckAnnotation.class);
        if (annotation == null) {
            return true;
        } else {
            // 有@AdminRoleCheckAnnotation注解的方法，判断当前后台登陆的角色是否满足要求
            HttpSession session = ServletUtil.getSession();
            // session中的用户的等级
            Integer userLevel = (Integer) session.getAttribute("userLevel");
            // 注解标注的最小的权限等级
            int allowedLevel = Integer.parseInt(annotation.value());
            if (userLevel >= allowedLevel) {
                return true;
            } else {
                log.info("当前用户 {} 权限不足,请求失败", session.getAttribute("loginUser"));
                throw new AdminUserAuthException();
            }
        }
    }
}
